package com.ag.contactTree;

import java.io.Serializable;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;

import com.ag.bean.TbDeptType;
import com.ag.zhh.dao.DeptDAO;
import com.ag.zhh.dao.UserDeptDAO;
import com.ag.zhh.vo.Dept;
import com.ag.zhh.vo.UserDept;

/**
 * 药监内部通讯录树,保存在服务器内存 单例模式——线程安全
 * 
 * @author 张颢铧
 * 
 */

public class MedicineTree extends AbstractTree implements Serializable {
	private static Logger logger = Logger.getLogger(EmergencyTree.class);
	private volatile static MedicineTree instance = null;

	private static Object lock = new Object();

	private MedicineTree() {

	}

	public static MedicineTree getInstance(UserDeptDAO deptDao) {
		try {
			System.out.println("/n/n&^&^&^&^&&^&&^&&^&^&^&^\n\n");
			if (instance == null) {
				synchronized (lock) {
					if (instance == null) {
						instance = new MedicineTree();
						logger.info("MedicineTree-----------reloading");
						instance.reloadMedicineDept(deptDao);
					}
				}
			
			}
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		return instance;
	}

	@Override
	protected TreeNode transform(Object info) {
		// 将Object对象转换为树的结点
		UserDept dept = (UserDept) info;
		TreeNode node = new TreeNode();
		node.setNodeId(dept.getUdId());
		if (dept.getTbUserDept() != null) {
			node.setParentId(dept.getTbUserDept().getUdId());
		}
		node.setBindData(dept);
		return node;
	}

	public synchronized void reloadMedicineDept(UserDeptDAO deptDao) {
		List<UserDept> nodes;
		try {
			TbDeptType deptType = new TbDeptType();
			deptType.setDtId("0000");
			deptType.setDtName("广州市药监局");
			nodes = deptDao.findByDeptType(deptType);
			//nodes = deptDao.findAll();
			for(UserDept node:nodes)
			{
				System.out.println("MedicineTree 部门id："+node+" 部门名："+node);
			}
			super.reload(nodes);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public TreeNode getNextNode(String nodeId) {

		TreeNode node = null;
		TreeNode parent = getTreeNode(nodeId).getParent();
		Iterator it = parent.getChildren().iterator();

		int flag = 0;
		while (it.hasNext() && flag == 0) {

			node = (TreeNode) it.next();
			System.out.println("-----------------下一个结点：" + node.getNodeId()
					+ "----------------------");
			if (node.getNodeId().equals(nodeId)) {

				if (it.hasNext()) {
					node = (TreeNode) it.next();
				} else
					node = null;
				flag = 1;
			}
		}
		if (flag == 0)
			node = null;

		return node;
	}

	public TreeNode getFirstChild(String nodeId) {

		TreeNode node = getTreeNode(nodeId);
		if (node == null)
			return null;

		else if (node.getChildren().size() == 0)
			return null;
		else
			return (TreeNode) node.getChildren().get(0);
	}

}
